package com.johnny.cms.core.controller.nob;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import au.com.bytecode.opencsv.CSVWriter;

import com.johnny.cms.core.service.CmsNOBService;
import com.johnny.core.helper.JsonHelper;
import com.johnny.core.hibernate.orm.Page;
import com.johnny.core.web.Webs;
import com.johnny.core.web.Webs.ContentType;
import com.johnny.core.web.controller.ControllerSupport;
import com.johnny.core.web.filter.JqGridFilter;
import com.johnny.nob.domain.NboContact;

@Controller(value = "nbocontactC")
@RequestMapping("/nbo-contact")
public class NobContactController extends ControllerSupport {
	@Autowired
	private CmsNOBService cmsNOBService;

	@RequestMapping(value = "/create/", method = POST)
	public void create(NboContact contact, HttpServletResponse response) {
		cmsNOBService.createNobContact(contact);
	}

	@RequestMapping(value = "/generate/")
	public void generate(HttpServletResponse response) throws IOException {
		Webs.prepareDownload(response, "nbo-contact.csv", ContentType.OCTET);
		List<NboContact> contacts = cmsNOBService.getAllNobContacts();

		CSVWriter writer = new CSVWriter(response.getWriter());
		String[] header = { "name", "email", "contact" };
		writer.writeNext(header);
		String[] data;
		for (NboContact s : contacts) {
			data = new String[] { s.getName(), s.getEmail(), s.getContact() };
			writer.writeNext(data);
		}
	}

	private NboContact nobContact = new NboContact();

	@RequestMapping(value = "/{filter}/views/", method = GET)
	public void views(@PathVariable("filter") String id, Page<NboContact> page,
			HttpServletResponse response) {
		JqGridFilter jqGridFilter = JsonHelper.fromJsonString(id,
				JqGridFilter.class);

		cmsNOBService.findNobContactByPage(page, jqGridFilter.getRules(
				nobContact, null));
		writeJson(response, JsonHelper.toJsonString(page, null, "father",
				"articleTemplate", "notEmptyFlashes", "photos", "firstPhoto",
				"notEmptyPhotos", "firstFlash", "flashes", "selfTemplatePath",
				"content"));
	}

	@RequestMapping(value = "/list/", method = GET)
	public String list(Model model) {

		return listView();
	}

	@Override
	protected String getViewPackage() {
		return "nbo-contact";
	}
}
